﻿using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Web.Security;
using CottagesOfHope.Core.Concrete;
using WebMatrix.WebData;

namespace CottagesOfHope.Migrations
{

    internal sealed class Configuration : DbMigrationsConfiguration<CottagesOfHopeDb>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(CottagesOfHopeDb context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            SeedMembership();
        }

        private void SeedMembership()
        {
            WebSecurity.InitializeDatabaseConnection("CottagesOfHopeDb",
        "User", "UserId", "UserName", autoCreateTables: true);

            var roles = (SimpleRoleProvider) Roles.Provider;

            if (!roles.RoleExists("Admin"))
            {
                roles.CreateRole("Admin");
            }

            if (!roles.RoleExists("Coach"))
            {
                roles.CreateRole("Coach");
            }

            if (!roles.RoleExists("Staff"))
            {
                roles.CreateRole("Staff");
            }

            if (!roles.RoleExists("Volunteer"))
            {
                roles.CreateRole("Volunteer");
            }

            if (!roles.RoleExists("Client"))
            {
                roles.CreateRole("Client");
            }

            var membership = (SimpleMembershipProvider) Membership.Provider;

            if (membership.GetUser("CottagesOfHope", false) == null)
            {
                membership.CreateUserAndAccount("CottagesOfHope", "CottagesOfHope123");
            }

            if (!roles.GetRolesForUser("CottagesOfHope").Contains("Admin"))
            {
                roles.AddUsersToRoles(new [] {"CottagesOfHope"}, new [] {"admin"});
            }
        }
    }
}
